package com.jhm.internet1;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/*
* 接收数据包
* */
public class MyInternetDemo3 {
    public static void main(String[] args) throws Exception {
        DatagramSocket datagramSocket = new DatagramSocket(10086);
        byte[] buf = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length);
        //该方法是阻塞的
        //程序执行到这里的时候会一直等待，知道发送端发送消息，才继续往下执行
        datagramSocket.receive(datagramPacket);
        //解析数据包
        byte[] data = datagramPacket.getData();
        int length = datagramPacket.getLength();
        System.out.println("接收到数据"+new String(data,0,length));
        InetAddress address = datagramPacket.getAddress();
        int port = datagramPacket.getPort();
        System.out.println("数据包是从"+address.getHostAddress()+":"+port+"发出的");

    }
}
